﻿/*
Copyright (c) 2013, Bartłomiej Gałkowski
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met: 

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer. 
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution. 

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

using System;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Diagnostics;



namespace PyroGen
{ 
    public partial class MainScreen : Form
    {


        public static DebugConsole Console;
        
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            switch (keyData)
            {
                case Keys.F5:
                    RunCurrentFile();
                    break;
                case Keys.O | Keys.Control:
                    OpenFileInTab();
                    break;
                case Keys.S | Keys.Control:
                    SaveCurrentFile();
                    break;

                case Keys.Z | Keys.Control:
                    UndoLastAction();
                    break;
                case Keys.Y | Keys.Control:
                    RedoLastAction();
                    break;

                case Keys.X | Keys.Control:
                    CutToClipboard();
                    break;
                case Keys.C | Keys.Control:
                    CopyToClipboard();
                    break;
                case Keys.V | Keys.Control:
                    PasteFromClipboard();
                    break;
            }

            return base.ProcessCmdKey(ref msg, keyData);
        }


        private void NewSelectedSourceTab(string fileName)
        {
            Text = fileName + " - " +  PyrogenCodeGenerator.VersionString;
            var page = new SourceCodeTabPage(fileName,contextMenuStrip);
            tabControl.TabPages.Add(page);
            tabControl.SelectedTab = page;
        }

        private void NewSelectedOutputTab(string text, string sourcefileName, bool isError)
        {
            //TODO: Path.GetFilename or of configure this in config
            Text = sourcefileName + " - " + PyrogenCodeGenerator.VersionString;
            OutputCodeTabPage page = new OutputCodeTabPage(text, sourcefileName, isError);

            tabControl.TabPages.Add(page);
            tabControl.SelectedTab = page;
        }

        public void OpenDefaultFile()
        {
            string name = SettingsLoader.GetDefaultFile();
            string dir = Directory.GetCurrentDirectory();
            if (name != null)
            {
                NewSelectedSourceTab(Path.Combine(dir, name));
            }
        }

        private void OpenFileInTab()
        {
            OpenFileDialog opfdialog = new OpenFileDialog();
            DialogResult result = opfdialog.ShowDialog();
            if (result == DialogResult.OK)
                NewSelectedSourceTab(opfdialog.FileName);
        }

        

        private void RunCurrentFile()
        {
            
            if(tabControl.SelectedTab != null)
            {

                SourceCodeTabPage page = (SourceCodeTabPage) tabControl.SelectedTab;
                if (page.Path == null)
                    return;
                string text = page.Run();
                if(page.HasChildTabPage())
                {
                    var child = page.GetChildTabPage();
                    tabControl.SelectedTab = child;
                    child.SetNewText(text);
                }
                NewSelectedOutputTab(text, page.Path, page.FailedLastRun);

            }


        }

        private void SaveCurrentFile()
        {
            CodeTabPage pagee = (CodeTabPage)tabControl.SelectedTab;
            if(pagee.Path != null)
                pagee.SourceCodeTextBox.SaveFile(pagee.Path, RichTextBoxStreamType.PlainText);
            else
            {
                SaveFileDialog sfdialog = new SaveFileDialog();
                DialogResult result = sfdialog.ShowDialog();
                if (result == DialogResult.OK)
                {
                    pagee.Path = sfdialog.FileName;
                    pagee.SourceCodeTextBox.SaveFile(pagee.Path, RichTextBoxStreamType.PlainText);
                }
         
            }
        }

        public MainScreen()
        {
            InitializeComponent();
            OpenDefaultFile();

            
            Console = new DebugConsole();
           // Console.Show();
            Console.SetDesktopLocation(DesktopLocation.X + 200 + Width, 50+ DesktopLocation.Y);
        }

        private void UndoLastAction()
        {
            GetCurrentCodeTextBox().Undo();
        }

        private void RedoLastAction()
        {
            GetCurrentCodeTextBox().Redo();
        }

        private void CutToClipboard()
        {
            GetCurrentCodeTextBox().Cut();
        }

        private void CopyToClipboard()
        {
            GetCurrentCodeTextBox().Copy();
        }

        private void SelectAll()
        {
            GetCurrentCodeTextBox().SelectAll();
        }

        private void DeleteText()
        {
            GetCurrentCodeTextBox().SelectedText = "";
        }

        private CodeTextBox GetCurrentCodeTextBox()
        {
            CodeTabPage page = (CodeTabPage)tabControl.SelectedTab;
            
            return page.SourceCodeTextBox;
        }

        private void PasteFromClipboard()
        {
            GetCurrentCodeTextBox().Paste();
        }
 
        private void OpenButtonClick(object sender, EventArgs e)
        {
            OpenFileInTab();
        }



        private void RunButtonClick(object sender, EventArgs e)
        {
            if (((CodeTabPage)tabControl.SelectedTab).Path == null)
                SaveCurrentFile();
            if (((CodeTabPage)tabControl.SelectedTab).Path != null)
                RunCurrentFile();
        }

        private void SaveButtonClick(object sender, EventArgs e)
        {
            SaveCurrentFile();
            TabControlSelectedIndexChanged(null, null);
        }

        private void UndoButtonClick(object sender, EventArgs e)
        {
            UndoLastAction();
        }

        private void RedoButtonClick(object sender, EventArgs e)
        {
            RedoLastAction();
        }



        private void NewSourceCodeTab(object sender, EventArgs e)
        {
            SourceCodeTabPage page = new SourceCodeTabPage();
            tabControl.TabPages.Add(page);
            tabControl.SelectedTab = page;
        }


        private void CutButtonClick(object sender, EventArgs e)
        {
            CutToClipboard();
        }

        private void CopyButtonClick(object sender, EventArgs e)
        {
            CopyToClipboard();
        }

        private void PasteButtonClick(object sender, EventArgs e)
        {
            PasteFromClipboard();
        }

        private void UpdateButtonAndTabState()
        {
            if(tabControl.SelectedTab.Text.Contains("[output]") && ((CodeTabPage)tabControl.SelectedTab).Path == null)
                runButton.Enabled = false;
            else
                runButton.Enabled = true;


        }


        private void TabControlSelectedIndexChanged(object sender, EventArgs e)
        {
            UpdateButtonAndTabState();

        }

        private void TabControlMouseClick(object sender, MouseEventArgs e)
        {
           
            var tabs = tabControl.TabPages;

            if (e.Button == MouseButtons.Middle)
            {
                tabs.Remove(tabs.Cast<TabPage>()
                        .Where((t, i) => tabControl.GetTabRect(i).Contains(e.Location))
                        .First());
                return;
            }


            if (e.Button == MouseButtons.Left)
            if(tabs.Cast<TabPage>().Where((t, i) => tabControl.ClickInXBox(e.Location,i)).Count() > 0)
            {
                tabs.Remove(tabs.Cast<TabPage>()
                        .Where((t, i) => tabControl.ClickInXBox(e.Location,i))
                        .First());
                return;
            }
        }

        private void undoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UndoLastAction();
        }

        private void redoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RedoLastAction();
        }

        private void cutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CutToClipboard();
        }

        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CopyToClipboard();
        }

        private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PasteFromClipboard();
        }

        private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SelectAll();
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DeleteText();
        }




    }
}
